<template>
  <div class="stocking-container">
    <!-- 时间查询按钮 -->
    <el-card class="time-filter-card" shadow="hover">
      <div class="time-filter-buttons">
        <el-button
          :type="activeTimeFilter === 'today' ? 'primary' : 'default'"
          @click="setTimeFilter('today')"
          class="time-btn"
        >
          今日
        </el-button>
        <el-button
          :type="activeTimeFilter === 'yesterday' ? 'primary' : 'default'"
          @click="setTimeFilter('yesterday')"
          class="time-btn"
        >
          昨日
        </el-button>
        <el-button
          :type="activeTimeFilter === 'thisWeek' ? 'primary' : 'default'"
          @click="setTimeFilter('thisWeek')"
          class="time-btn"
        >
          本周
        </el-button>
        <el-button
          :type="activeTimeFilter === 'lastWeek' ? 'primary' : 'default'"
          @click="setTimeFilter('lastWeek')"
          class="time-btn"
        >
          上周
        </el-button>
        <el-button
          :type="activeTimeFilter === 'thisMonth' ? 'primary' : 'default'"
          @click="setTimeFilter('thisMonth')"
          class="time-btn"
        >
          本月
        </el-button>
        <el-button
          :type="activeTimeFilter === 'lastMonth' ? 'primary' : 'default'"
          @click="setTimeFilter('lastMonth')"
          class="time-btn"
        >
          上月
        </el-button>
        <el-button
          :type="activeTimeFilter === 'custom' ? 'primary' : 'default'"
          @click="setTimeFilter('custom')"
          class="time-btn"
        >
          自定义时间
        </el-button>
      </div>
    </el-card>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索表单卡片 -->
      <el-card class="search-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Search /></el-icon>
            <span>查询条件</span>
          </div>
        </template>

        <el-form :model="formInline" class="search-form">
          <div class="form-grid">
            <div class="form-item">
              <el-form-item label="货品名称">
                <el-input
                  v-model="formInline.Product_Name"
                  placeholder="请输入货品名称/编号"
                  clearable
                />
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘点单号">
                <el-input
                  v-model="formInline.StocktakingCode"
                  placeholder="请输入盘点单号"
                  clearable
                />
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="单位">
                <el-select
                  v-model="formInline.Unit_ID"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in unit"
                    :label="item.unit_Name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="部门">
                <el-select
                  v-model="formInline.Department_ID"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in deplarments"
                    :label="item.department_Name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="货品类别">
                <el-tree-select
                v-model="formInline.Category_ID"
                :data="categoryTreeList"
                placeholder="请选择"
                clearable
                check-strictly
                :props="{
                  children: 'children',
                  label: 'category_Name',
                  value: 'id',
                }"
                style="width: 200px"
              />
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="仓库名称">
                <el-select
                  v-model="formInline.Warehouse_ID"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in deplarment"
                    :label="item.warehouse_Name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="经办人">
                <el-input
                  v-model="formInline.Reviewer"
                  placeholder="请输入经办人"
                  clearable
                />
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘盈数量">
                <div class="range-input">
                  <el-input
                    v-model="formInline.YingStocktakingCountStart"
                    placeholder="最小值"
                    clearable
                  />
                  <span class="range-separator">~</span>
                  <el-input
                    v-model="formInline.YingStocktakingCountEnd"
                    placeholder="最大值"
                    clearable
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘亏数量">
                <div class="range-input">
                  <el-input
                    v-model="formInline.KuiStocktakingCountStart"
                    placeholder="最小值"
                    clearable
                  />
                  <span class="range-separator">~</span>
                  <el-input
                    v-model="formInline.KuiStocktakingCountEnd"
                    placeholder="最大值"
                    clearable
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘盈金额">
                <div class="range-input">
                  <el-input
                    v-model="formInline.YingStocktakingPriceStart"
                    placeholder="最小值"
                    clearable
                  />
                  <span class="range-separator">~</span>
                  <el-input
                    v-model="formInline.YingStocktakingPriceEnd"
                    placeholder="最大值"
                    clearable
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘亏金额">
                <div class="range-input">
                  <el-input
                    v-model="formInline.KuiStocktakingPriceStart"
                    placeholder="最小值"
                    clearable
                  />
                  <span class="range-separator">~</span>
                  <el-input
                    v-model="formInline.KuiStocktakingPPriceEnd"
                    placeholder="最大值"
                    clearable
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="盘点结果">
                <div class="checkbox-group">
                  <el-checkbox v-model="formInline.resultAll" label="全部" />
                  <el-checkbox
                    v-model="formInline.resultSurplus"
                    label="盘盈"
                  />
                  <el-checkbox v-model="formInline.resultLoss" label="盘亏" />
                  <el-checkbox
                    v-model="formInline.resultNoChange"
                    label="无盈亏"
                  />
                </div>
              </el-form-item>
            </div>
          </div>

          <div class="form-actions">
            <el-button type="default" @click="resetForm()" class="reset-btn">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="getdata()" class="search-btn">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
          </div>
        </el-form>
      </el-card>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-card class="stats-card count-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">{{ totalStocktakingCount }}</div>
            <div class="stats-label">盘点次数</div>
          </div>
          <div class="stats-icon">
            <el-icon><List /></el-icon>
          </div>
        </el-card>

        <el-card class="stats-card surplus-count-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">{{ totalSurplusCount }}</div>
            <div class="stats-label">盘盈数量</div>
          </div>
          <div class="stats-icon">
            <el-icon><ArrowUp /></el-icon>
          </div>
        </el-card>

        <el-card class="stats-card loss-count-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">{{ totalLossCount }}</div>
            <div class="stats-label">盘亏数量</div>
          </div>
          <div class="stats-icon">
            <el-icon><ArrowDown /></el-icon>
          </div>
        </el-card>

        <el-card class="stats-card surplus-amount-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">¥{{ totalSurplusAmount }}</div>
            <div class="stats-label">盘盈成本总额</div>
          </div>
          <div class="stats-icon">
            <el-icon><Money /></el-icon>
          </div>
        </el-card>

        <el-card class="stats-card loss-amount-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">¥{{ totalLossAmount }}</div>
            <div class="stats-label">盘亏成本总额</div>
          </div>
          <div class="stats-icon">
            <el-icon><Money /></el-icon>
          </div>
        </el-card>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="default" @click="handleExport()" class="export-btn">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="primary" @click="getdata()" class="refresh-btn">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>盘点明细数据</span>
          </div>
        </template>

        <el-table
          :data="tableData"
          style="width: 100%"
          class="custom-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="product_Number" label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="product_Number" label="货品编号" width="120" />
          <el-table-column prop="product_Name" label="货品名称" width="150" />
          <el-table-column prop="stocktakingType" label="盘点结果" width="100">
            <template #default="scope">
              <el-tag
                :type="getStocktakingResultType(scope.row.stocktakingType)"
                size="small"
              >
                {{ scope.row.stocktakingType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="specifications" label="规格型号" width="120" />
          <el-table-column prop="unit_Name" label="单位" width="80" />
          <el-table-column prop="category_Name" label="货品类型" width="120" />
          <el-table-column
            prop="stocktakingCode"
            label="盘点单号"
            width="120"
          />
          <el-table-column prop="internal_Code" label="条码" width="120" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="150" />
          <el-table-column
            prop="ruMinusChuCount"
            label="账面数量"
            width="100"
          />
          <el-table-column
            prop="yingPlusKuiCount"
            label="盘点数量"
            width="100"
          />
          <el-table-column
            prop="yingStocktakingCount"
            label="盘盈数量"
            width="100"
          >
            <template #default="scope">
              <span class="surplus-count">{{
                scope.row.yingStocktakingCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="kuiStocktakingCount"
            label="盘亏数量"
            width="100"
          >
            <template #default="scope">
              <span class="loss-count">{{
                scope.row.kuiStocktakingCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="chuMinusRuPrice" label="账面金额" width="120">
            <template #default="scope">
              <span class="amount-value">¥{{ scope.row.chuMinusRuPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="yingPlusKuiPrice" label="盘点金额" width="120">
            <template #default="scope">
              <span class="amount-value"
                >¥{{ scope.row.yingPlusKuiPrice }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="yingStocktakingPrice"
            label="盘盈金额"
            width="120"
          >
            <template #default="scope">
              <span class="surplus-amount"
                >¥{{ scope.row.yingStocktakingPrice }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="kuiStocktakingPrice"
            label="盘亏金额"
            width="120"
          >
            <template #default="scope">
              <span class="loss-amount"
                >¥{{ scope.row.kuiStocktakingPrice }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="price" label="成本单价" width="100">
            <template #default="scope">
              <span class="price-value">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="yingPlusKuiPrice" label="成本金额" width="120">
            <template #default="scope">
              <span class="amount-value"
                >¥{{ scope.row.yingPlusKuiPrice }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="reviewer" label="经办人" width="100" />
          <el-table-column prop="createUse" label="制单人" width="100">
            <template v-slot="scoped">
              <span v-if="scoped.row.createUse == '10032'">吴维昊</span>
              <span v-if="scoped.row.createUse == '10036'">王雨龙</span>
              <span v-if="scoped.row.createUse == '10037'">张可欣</span>
              <span v-if="scoped.row.createUse == '10038'">赵姝雅</span>
              <span v-if="scoped.row.createUse == '10039'">段栋兴</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="department_Name"
            label="所在部门"
            width="120"
          />
          <el-table-column prop="createTime" label="制单时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="page.totalCount"
            class="custom-pagination"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { reactive, onMounted, ref, watch, computed } from "vue";
import { BasicsRed } from "@/http/axiosHelper";
import { ElMessage, ElMessageBox } from "element-plus";
import { BasicsWrite } from "@/http/axiosHelper";
import { useRouter } from "vue-router";
import { StorageRed } from "@/http/axiosHelper";
// import { StorageRed } from "@/http/axiosHelper";
import {
  Box,
  Search,
  Document,
  Refresh,
  ArrowDown,
  ArrowUp,
  Money,
  List,
  Download,
  Goods,
  User,
  UserFilled,
  Shop,
} from "@element-plus/icons-vue";

const router = useRouter();
const dialogVisible = ref(false);

// 时间筛选相关
const activeTimeFilter = ref("today");

// 设置时间筛选
const setTimeFilter = (filter: string) => {
  activeTimeFilter.value = filter;
  // 根据选择的时间范围设置日期
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  switch (filter) {
    case "today":
      formInline.CreateTimeStartTime = today;
      formInline.CreateTimeEndTime = today;
      break;
    case "yesterday":
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      formInline.CreateTimeStartTime = yesterday;
      formInline.CreateTimeEndTime = yesterday;
      break;
    case "thisWeek":
      const weekStart = new Date(today);
      weekStart.setDate(today.getDate() - today.getDay());
      formInline.CreateTimeStartTime = weekStart;
      formInline.CreateTimeEndTime = today;
      break;
    case "lastWeek":
      const lastWeekStart = new Date(today);
      lastWeekStart.setDate(today.getDate() - today.getDay() - 7);
      const lastWeekEnd = new Date(lastWeekStart);
      lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
      formInline.CreateTimeStartTime = lastWeekStart;
      formInline.CreateTimeEndTime = lastWeekEnd;
      break;
    case "thisMonth":
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      formInline.CreateTimeStartTime = monthStart;
      formInline.CreateTimeEndTime = today;
      break;
    case "lastMonth":
      const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
      formInline.CreateTimeStartTime = lastMonthStart;
      formInline.CreateTimeEndTime = lastMonthEnd;
      break;
    case "custom":
      // 自定义时间，不清空日期，让用户手动选择
      break;
  }

  if (filter !== "custom") {
    getdata();
  }
};

// 定义数据类型接口
interface StockingItem {
  product_Number: string;
  product_Name: string;
  stocktakingType: string;
  specifications: string;
  unit_Name: string;
  category_Name: string;
  stocktakingCode: string;
  internal_Code: string;
  warehouse_Name: string;
  ruMinusChuCount: number;
  yingPlusKuiCount: number;
  yingStocktakingCount: number;
  kuiStocktakingCount: number;
  chuMinusRuPrice: number;
  yingPlusKuiPrice: number;
  yingStocktakingPrice: number;
  kuiStocktakingPrice: number;
  price: number;
  reviewer: string;
  createUse: string;
  department_Name: string;
  createTime: string;
  [key: string]: any;
}

// 首先定义所有的响应式数据
const tableData = ref<StockingItem[]>([]);
const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
});



const formInline = reactive({
  Warehouse_Code: "",
  Warehousing_Type: "",
  StocktakingCode: "",
  Warehouse_ID: null,
  Reviewer: "",
  Product_Name: "",
  Category_ID: null,
  Unit_ID: null,
  CreateTimeStartTime: null as Date | null,
  CreateTimeEndTime: null as Date | null,
  ReviewTimeStartTime: null as Date | null,
  ReviewTimeEndTime: null as Date | null,
  CreateUse: null,
  Department_ID: null,
  YingStocktakingCountStart: null,
  YingStocktakingCountEnd: null,
  KuiStocktakingCountStart: null,
  KuiStocktakingCountEnd: null,
  YingStocktakingPriceStart: null,
  YingStocktakingPriceEnd: null,
  KuiStocktakingPriceStart: null,
  KuiStocktakingPPriceEnd: null,
  resultAll: false,
  resultSurplus: false,
  resultLoss: false,
  resultNoChange: false,
});

// 其他ref定义
const unit = ref();
const ProductCategory = ref();
const deplarments = ref();
const deplarment = ref();

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

// 计算统计数据
const totalStocktakingCount = computed(() => {
  return tableData.value.length;
});

const totalSurplusCount = computed(() => {
  return tableData.value.reduce(
    (sum, item) => sum + (item.yingStocktakingCount || 0),
    0
  );
});

const totalLossCount = computed(() => {
  return tableData.value.reduce(
    (sum, item) => sum + (item.kuiStocktakingCount || 0),
    0
  );
});

const totalSurplusAmount = computed(() => {
  return tableData.value
    .reduce((sum, item) => sum + (item.yingStocktakingPrice || 0), 0)
    .toFixed(2);
});

const totalLossAmount = computed(() => {
  return tableData.value
    .reduce((sum, item) => sum + (item.kuiStocktakingPrice || 0), 0)
    .toFixed(2);
});

// 获取盘点结果类型
const getStocktakingResultType = (type: string) => {
  switch (type) {
    case "盘盈":
      return "success";
    case "盘亏":
      return "danger";
    case "无盈亏":
      return "info";
    default:
      return "info";
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(formInline).forEach((key) => {
    if (
      key === "resultAll" ||
      key === "resultSurplus" ||
      key === "resultLoss" ||
      key === "resultNoChange"
    ) {
      (formInline as any)[key] = false;
    } else {
      (formInline as any)[key] = null;
    }
  });
  getdata();
};


// 产品类型树形列表
const categoryTreeList: any = ref([]);
// 获取产品类型树形结构
const getCategoryTreeList = () => {
  StorageRed({
    url: "/api/WorkOrder/GetProductCategoryTree",
    method: "get",
  }).then((res) => {
    categoryTreeList.value = res.data.data;
  });
};




// 盘点统计导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await StorageRed({
      url: "/api/WorkOrder/GetStocktakExport", // 后端接口地址
      method: "GET",
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
        Category_ID: formInline.Category_ID,
        CreateTimeEndTime: formInline.CreateTimeEndTime,
        CreateTimeStartTime: formInline.CreateTimeStartTime,
        CreateUse: formInline.CreateUse,
        Department_ID: formInline.Department_ID,
        Product_Name: formInline.Product_Name,
        ReviewTimeEndTime: formInline.ReviewTimeEndTime,
        ReviewTimeStartTime: formInline.ReviewTimeStartTime,
        Reviewer: formInline.Reviewer,
        StocktakingCode: formInline.StocktakingCode,
        Unit_ID: formInline.Unit_ID,
        Warehouse_Code: formInline.Warehouse_Code,
        KuiStocktakingCountEnd: formInline.KuiStocktakingCountEnd,
        KuiStocktakingCountStart: formInline.KuiStocktakingCountStart,
        KuiStocktakingPPriceEnd: formInline.KuiStocktakingPPriceEnd,
        KuiStocktakingPriceStart: formInline.KuiStocktakingPriceStart,
        YingStocktakingCountEnd: formInline.YingStocktakingCountEnd,
        YingStocktakingCountStart: formInline.YingStocktakingCountStart,
        YingStocktakingPriceEnd: formInline.YingStocktakingPriceEnd,
        YingStocktakingPriceStart: formInline.YingStocktakingPriceStart,
      }, // 对应后端 [FromQuery] 的 command 参数
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success("导出成功");
  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    ElMessage.error("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "库存盘点.xlsx"; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ""));
  }
  return "库存盘点.xlsx";
}
//获取数据
const getdata = () => {
  StorageRed.get("/api/WorkOrder/GetStocktakHandle", {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
      Category_ID: formInline.Category_ID,
      CreateTimeEndTime: formInline.CreateTimeEndTime,
      CreateTimeStartTime: formInline.CreateTimeStartTime,
      CreateUse: formInline.CreateUse,
      Department_ID: formInline.Department_ID,
      Product_Name: formInline.Product_Name,
      ReviewTimeEndTime: formInline.ReviewTimeEndTime,
      ReviewTimeStartTime: formInline.ReviewTimeStartTime,
      Reviewer: formInline.Reviewer,
      StocktakingCode: formInline.StocktakingCode,
      Unit_ID: formInline.Unit_ID,
      Warehouse_Code: formInline.Warehouse_Code,
      KuiStocktakingCountEnd: formInline.KuiStocktakingCountEnd,
      KuiStocktakingCountStart: formInline.KuiStocktakingCountStart,
      KuiStocktakingPPriceEnd: formInline.KuiStocktakingPPriceEnd,
      KuiStocktakingPriceStart: formInline.KuiStocktakingPriceStart,
      YingStocktakingCountEnd: formInline.YingStocktakingCountEnd,
      YingStocktakingCountStart: formInline.YingStocktakingCountStart,
      YingStocktakingPriceEnd: formInline.YingStocktakingPriceEnd,
      YingStocktakingPriceStart: formInline.YingStocktakingPriceStart,
    },
  }).then((res) => {
    tableData.value = res.data.data;
    page.totalCount = res.data.totalCount;
  });
};

//仓库下拉框
const delparmentdata = () => {
  StorageRed.get("/api/Warehouse_InOrOut/GetWarehouseModel").then(
    (res: any) => {
      deplarment.value = res.data.data;
    }
  );
};

//产品单位下拉框
const unitdata = () => {
  StorageRed.get("/api/WorkOrder/GetUnitDropdown").then((res: any) => {
    unit.value = res.data.data;
  });
};
//产品类型下拉框
const ProductCategorydata = () => {
  StorageRed.get("/api/WorkOrder/GetProductCategoryTree").then((res: any) => {
    ProductCategory.value = res.data.data;
  });
};
//部门下拉框
const delparmentdatas = () => {
  StorageRed.get("/api/WorkOrder/GetDepartmentDropdown").then((res: any) => {
    deplarments.value = res.data.data;
  });
};

// 监听器
watch(page, () => {
  getdata();
});

onMounted(() => {
  // 初始化时间筛选为今日
  setTimeFilter("today");
  delparmentdata();
  unitdata();
  delparmentdatas();
  ProductCategorydata();
  getCategoryTreeList();
});
</script>

<style scoped>
/* 主容器 */
.stocking-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 时间筛选卡片 */
.time-filter-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 24px;
}

.time-filter-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  overflow-x: auto;
  padding: 16px;
}

.time-btn {
  flex-shrink: 0;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  white-space: nowrap;
}

.time-btn.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.time-btn.el-button--default {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
}

.time-btn.el-button--default:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 移除页面头部相关样式 */

/* 主要内容区域 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-top: 0;
}

/* 搜索表单卡片 */
.search-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header .el-icon {
  font-size: 20px;
  color: #409eff;
}

.search-form {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  min-width: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-form .el-form-item__label {
  font-weight: 500;
  color: #2c3e50;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #6c757d;
  font-weight: 500;
}

.checkbox-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
  flex-wrap: nowrap;
}

.reset-btn,
.search-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  margin-right: 8px;
}

.reset-btn {
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  color: #6c757d;
}

.reset-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.search-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  color: #fff;
}

.search-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d6aad 100%);
}

/* 统计卡片 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

.stats-content {
  padding: 24px;
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #2c3e50;
}

.stats-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.stats-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 24px;
  opacity: 0.2;
  color: #2c3e50;
}

.count-card {
  border-left: 4px solid #409eff;
}

.count-card .stats-number {
  color: #409eff;
}

.surplus-count-card {
  border-left: 4px solid #67c23a;
}

.surplus-count-card .stats-number {
  color: #67c23a;
}

.loss-count-card {
  border-left: 4px solid #f56c6c;
}

.loss-count-card .stats-number {
  color: #f56c6c;
}

.surplus-amount-card {
  border-left: 4px solid #409eff;
}

.surplus-amount-card .stats-number {
  color: #409eff;
}

.loss-amount-card {
  border-left: 4px solid #e6a23c;
}

.loss-amount-card .stats-number {
  color: #e6a23c;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.export-btn,
.refresh-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  margin-right: 8px;
}

.export-btn {
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  color: #6c757d;
}

.export-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.refresh-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  color: white;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d6aad 100%);
}

/* 表格卡片 */
.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

/* 表格样式 */
.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background: #f8f9fa;
}

.custom-table :deep(.el-table__header) {
  color: #333;
  font-weight: 600;
}

.custom-table :deep(.el-table__body) {
  color: #2c3e50;
}

.custom-table :deep(.el-table__row) {
  color: #2c3e50;
}

/* 数据颜色样式 */
.amount-value {
  color: #2c3e50;
  font-weight: 600;
}

.surplus-count {
  color: #67c23a;
  font-weight: 600;
}

.loss-count {
  color: #f56c6c;
  font-weight: 600;
}

.surplus-amount {
  color: #67c23a;
  font-weight: 700;
}

.loss-amount {
  color: #f56c6c;
  font-weight: 700;
}

.price-value {
  color: #e6a23c;
  font-weight: 600;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.custom-pagination {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stocking-container {
    padding: 16px;
  }

  .stats-section {
    grid-template-columns: repeat(3, 1fr);
  }

  .form-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .time-filter-buttons {
    gap: 4px;
    padding: 12px;
  }

  .time-btn {
    padding: 6px 12px;
    font-size: 12px;
  }

  .form-actions {
    flex-direction: column;
    gap: 8px;
  }

  .reset-btn,
  .search-btn {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }

  .export-btn,
  .refresh-btn {
    width: 100%;
  }
}
</style>
